package fonkin.com.wifisignapp.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;

import java.io.Serializable;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import fonkin.com.wifisignapp.R;
import fonkin.com.wifisignapp.acticity.Launcher;
import fonkin.com.wifisignapp.acticity.LoginActivity;
import fonkin.com.wifisignapp.acticity.aboutMe.ResetPwd;
import fonkin.com.wifisignapp.acticity.addressList.SearchUser;
import fonkin.com.wifisignapp.acticity.proceeding.DeptUserDetail;
import fonkin.com.wifisignapp.acticity.sign.RecordView;
import fonkin.com.wifisignapp.adapter.news.UserAdapter;
import fonkin.com.wifisignapp.adapter.news.WifiAdapter;
import fonkin.com.wifisignapp.bean.app.BannerInfor;
import fonkin.com.wifisignapp.bean.user.User;
import fonkin.com.wifisignapp.retrofit.BaseRetrofit;
import fonkin.com.wifisignapp.utils.LocationUtils;
import fonkin.com.wifisignapp.utils.ReturnVo;
import fonkin.com.wifisignapp.utils.ShowToast;
import fonkin.com.wifisignapp.utils.WifiAdmin;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SignFragment extends Fragment implements AMapLocationListener {
    public static final String TAG = "MainActivity";
    TextView textView1;
    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;
    private TextView textView,connectionInfo;
    private String[] strMsg;
    private WifiAdapter wifiAdapter;
    private LinearLayout scan_wifi,signOut,signIn ;
    private ListView mlistView;
    private ImageView bgImage,historyRecord;
    protected WifiAdmin mWifiAdmin;
    private List<ScanResult> mWifiList;
    public int level;
    protected String ssid;
    private  SharedPreferences pref;

    private final long SPLASH_LENGTH = 5000;
    Handler handler = new Handler();

    public static SignFragment newInstance(String text){
        SignFragment signFragment=new SignFragment();
        Bundle bundle=new Bundle();
        bundle.putString("text",text);
        signFragment.setArguments(bundle);
        return signFragment;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.sign_fragment,container,false);
        textView1= (TextView) view.findViewById(R.id.textView);
        connectionInfo= (TextView) view.findViewById(R.id.connection_info);
        textView1.setText(getArguments().getString("text"));
        mWifiAdmin = new WifiAdmin(getActivity());
        // ShowToast.ShowToastShort("onCreateView2222",getActivity());
        IntentFilter filter = new IntentFilter(
                WifiManager.NETWORK_STATE_CHANGED_ACTION);
        //="android.net.wifi.STATE_CHANGE"  监听wifi状态的变化
        getActivity().registerReceiver(mReceiver, filter);

        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // ShowToast.ShowToastShort("onCreate1111111111",getActivity());
        Log.d("======",sHA1(getContext()));

    }

    public static String sHA1(Context context) {
        try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), PackageManager.GET_SIGNATURES);
            byte[] cert = info.signatures[0].toByteArray();
            MessageDigest md = MessageDigest.getInstance("SHA1");
            byte[] publicKey = md.digest(cert);
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < publicKey.length; i++) {
                String appendString = Integer.toHexString(0xFF & publicKey[i])
                        .toUpperCase(Locale.US);
                if (appendString.length() == 1)
                    hexString.append("0");
                hexString.append(appendString);
            }
            return hexString.toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        pref = PreferenceManager.getDefaultSharedPreferences(getContext());
        final String userId = pref.getString("user_id","");
        final String deptName = pref.getString("dept_name","");
        final String userName = pref.getString("user_name","");
        super.onActivityCreated(savedInstanceState);
      //  ShowToast.ShowToastShort("onActivityCreated",getActivity());
        bgImage = (ImageView)getView().findViewById(R.id.no_data_bg);
        bgImage.setVisibility(View.GONE);
        textView = (TextView)getView().findViewById(R.id.text_map);
        scan_wifi  =(LinearLayout)getView().findViewById(R.id.scan_wifi);
        historyRecord  =(ImageView) getView().findViewById(R.id.history_record);
        historyRecord.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               Intent intent = new Intent(getActivity(), RecordView.class);
               startActivity(intent);

            }
        });
        mlistView = (ListView)getView().findViewById(R.id.mlistView);

        scan_wifi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = mWifiAdmin.checkState(getActivity());
                if (i==3){
                    bgImage.setVisibility(View.GONE);
                    IntentFilter filter = new IntentFilter(
                            WifiManager.NETWORK_STATE_CHANGED_ACTION);
                    //="android.net.wifi.STATE_CHANGE"  监听wifi状态的变化
                    getActivity().registerReceiver(mReceiver, filter);
                    initWifiList();
                }else if(i == 1){
                    ShowToast.ShowToastShort("请先打开WiFI",getContext());
                }
            }
        });
        //签退
        signOut = (LinearLayout)getView().findViewById(R.id.sign_out_btn);
        signOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = mWifiAdmin.checkState(getActivity());
                if (i==3){
                    if (isWifi(getContext())){
                        BaseRetrofit.GetBaseRetrofit().signOut(pref.getString("user_id",""),pref.getString("user_name",""),pref.getString("dept_name",""),textView.getText().toString(),mWifiAdmin.getSSID()).enqueue(new Callback<ReturnVo<String>>() {
                            @Override
                            public void onResponse(Call<ReturnVo<String>> call, Response<ReturnVo<String>> response) {
                                if (response.body().getCode().equals(1)){
                                    ShowToast.CenterPicToast("辛苦了！！签退成功", getContext(), R.drawable.ic_check_circle_black_24dp);
                                }else if(response.body().getCode().equals(2)){
                                    ShowToast.ShowToastShort("很棒！！你已经签退过了",getContext());
                                }else{
                                    ShowToast.CenterPicToast("签退失败", getContext(), R.drawable.ic_clear_black_24dp);
                                }
                            }

                            @Override
                            public void onFailure(Call<ReturnVo<String>> call, Throwable t) {

                            }
                        });
                    }else{
                        ShowToast.ShowToastShort("连接失败",getActivity());
                    }
                }else if(i == 1){
                    ShowToast.ShowToastShort("请先打开WiFI",getContext());
                }
            }
        });
        //签到
        signIn = (LinearLayout)getView().findViewById(R.id.sign_in_btn);
        signIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int i = mWifiAdmin.checkState(getActivity());
                if (i==3){
                    if (isWifi(getContext())){
                        BaseRetrofit.GetBaseRetrofit().signIn(pref.getString("user_id",""),pref.getString("user_name",""),pref.getString("dept_name",""),textView.getText().toString(),mWifiAdmin.getSSID()).enqueue(new Callback<ReturnVo<String>>() {
                            @Override
                            public void onResponse(Call<ReturnVo<String>> call, Response<ReturnVo<String>> response) {
                                if (response.isSuccessful()) {
                                    if (response.body().getCode().equals(1)){
                                        ShowToast.CenterPicToast("签到成功", getContext(), R.drawable.ic_check_circle_black_24dp);
                                    }else if(response.body().getCode().equals(2)){
                                        ShowToast.ShowToastShort("神准时！！你已经签到过了",getContext());
                                    }else{
                                        ShowToast.CenterPicToast("签到失败", getContext(), R.drawable.ic_clear_black_24dp);
                                    }

                                }
                            }
                            @Override
                            public void onFailure(Call<ReturnVo<String>> call, Throwable t) {

                            }
                        });
                    }else{
                        ShowToast.ShowToastShort("连接失败",getActivity());
                    }
                }else if(i == 1){
                    ShowToast.ShowToastShort("请先打开WiFI",getContext());
                }
            }
        });
        initWifiList();
        Location();



    }


    /**
     * 判断是否连接
     * @param mContext
     * @return
     */
    private  boolean isWifi(Context mContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return true;
        }
        return false;
    }

    public void initWifiList(){
        mWifiList = mWifiAdmin.startScan(getActivity());
        if(!mWifiList.isEmpty()){
           // mlistView.setAdapter(new MyAdapter(getContext(),mWifiList));
          // setListViewHeightBasedOnChildren(mlistView);

            wifiAdapter = new WifiAdapter(getActivity(),new ArrayList<ScanResult>());
            mlistView.setAdapter(wifiAdapter);
            wifiAdapter.addAll(mWifiList);
            mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    ScanResult scanResult = mWifiList.get(position);
                    ShowToast.ShowToastLong(scanResult.BSSID,getActivity());
                    AlertDialog.Builder alert=new AlertDialog.Builder(getActivity());
                    ssid=mWifiList.get(position).SSID;
                    alert.setTitle(ssid);
                    alert.setMessage("输入密码");
                    final EditText et_password=new EditText(getActivity());
                  //  final SharedPreferences preferences=getSharedPreferences("wifi_password", Context.MODE_PRIVATE);
                 //   et_password.setText(preferences.getString(ssid, ""));
                    alert.setView(et_password);
                    //alert.setView(view1);
                    alert.setPositiveButton("连接", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            String pw = et_password.getText().toString();
                            if(null == pw){
                                Toast.makeText(getActivity(), "请输入妈妈", Toast.LENGTH_SHORT).show();
                                return;
                            }
                        //    SharedPreferences.Editor editor=preferences.edit();
                         //   editor.putString(ssid, pw);   //保存密码
                         //   editor.commit();
                            mWifiAdmin.addNetwork(mWifiAdmin.CreateWifiInfo(ssid, et_password.getText().toString(), 3));
                            handler.postDelayed(new Runnable() {  //使用handler的postDelayed实现延时跳转

                                public void run() {
                                    IntentFilter filter = new IntentFilter(
                                            WifiManager.NETWORK_STATE_CHANGED_ACTION);
                                    getActivity().registerReceiver(mReceiver, filter);
                                }
                            }, SPLASH_LENGTH);
                        }
                    });
                    alert.setNegativeButton("取消", new DialogInterface.OnClickListener(){
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //
                            //mWifiAdmin.removeWifi(mWifiAdmin.getNetworkId());
                        }
                    });
                    alert.create();
                    alert.show();


                }
            });

        }else{
            bgImage.setVisibility(View.VISIBLE);
            Picasso
                    .with(getContext())
                    .load(R.drawable.none_data)
                    .resize(500,400)
                    .into(bgImage);
        }
    }



        public void setListViewHeightBasedOnChildren(ListView listView) {
            ListAdapter listAdapter = listView.getAdapter();
            if (listAdapter == null) {
                return;
            }
            int totalHeight = 0;
            for (int i = 0; i < listAdapter.getCount(); i++) {
                View listItem = listAdapter.getView(i, null, listView);
                listItem.measure(0, 0);
                totalHeight += listItem.getMeasuredHeight();
            }
            ViewGroup.LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
            listView.setLayoutParams(params);
        }



    //监听wifi状态
    private BroadcastReceiver mReceiver = new BroadcastReceiver (){
        @Override
        public void onReceive(Context context, Intent intent) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo wifiInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
            if(wifiInfo.isConnected()){
                WifiManager wifiManager = (WifiManager) context
                        .getSystemService(Context.WIFI_SERVICE);
                String wifiSSID = wifiManager.getConnectionInfo()
                        .getSSID();
                connectionInfo.setText("成功连接："+wifiSSID);
            }else{
                connectionInfo.setText("请连接可用WiFi");
            }
        }

    };


    @Override
    public void onLocationChanged(AMapLocation loc) {
        if (null != loc) {
            Message msg = mHandler.obtainMessage();
            msg.obj = loc;
            msg.what = LocationUtils.MSG_LOCATION_FINISH;
            mHandler.sendMessage(msg);
        }

    }

    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                //定位完成
                case LocationUtils.MSG_LOCATION_FINISH:
                    String result = "";
                    try {
                        AMapLocation loc = (AMapLocation) msg.obj;
                        result = LocationUtils.getLocationStr(loc, 1);
                        strMsg = result.split(",");
                        Toast.makeText(getActivity(), "定位成功", Toast.LENGTH_LONG).show();
                       // textView.setText("地址：" + strMsg[0] + "\n" + "经    度：" + strMsg[1] + "\n" + "纬    度：" + strMsg[1]);
                      textView.setText(strMsg[0]);
                        //textView.setText("qwewrer");
                    } catch (Exception e) {
                        Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_LONG).show();
                    }
                    break;
                default:
                    break;
            }
        };

    };

    public void Location() {
        // TODO Auto-generated method stub
        try {
            locationClient = new AMapLocationClient(getActivity());
            locationOption = new AMapLocationClientOption();
            // 设置定位模式为低功耗模式
            locationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            // 设置定位监听
            locationClient.setLocationListener(this);
            locationOption.setOnceLocation(true);//设置为单次定位
            locationClient.setLocationOption(locationOption);// 设置定位参数
            // 启动定位
            locationClient.startLocation();
            mHandler.sendEmptyMessage(LocationUtils.MSG_LOCATION_START);
        } catch (Exception e) {
            Toast.makeText(getActivity(), "定位失败", Toast.LENGTH_LONG).show();
        }
    }



}
